﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GAM_Web_Designer_Pro.Properties;
using GAM_Web_Designer_Pro.Classes;
using ColorRichTextBox.ColorRichTextBox;
using mshtml;
using System.IO;

namespace GAM_Web_Designer_Pro.Forms {
    public partial class DocumentForm : Form {
        
        private clsColorRichTextBox rtb;
        private clsColorRichTextBoxSchema schema;
        private string _currentDocumentPath;
        private string _currentTemporyFile;
        private MainForm _parent;
        private AutoSave autoSave;        
        private bool beenEdited;
        private IHTMLDocument2 docv;
        private bool wasDesigning = false;
        private bool isLoaded = false;

        public bool WasDesigning {
            get {
                return wasDesigning;
            }
            set {
                wasDesigning = value;
            }
        }

        public bool HasBeenEdited {
            get {
                return beenEdited;
            }
            set {
                beenEdited = value;
            }
        }

        #region " Public Methods "

        public DocumentForm( string path, clsColorRichTextBoxSchema schema, MainForm parent ) {
            InitializeComponent();
            this.FormClosing += new FormClosingEventHandler( this.DocumentForm_FormClosing );
            this.Shown += new EventHandler( this.DocumentForm_FormShow );
            this.schema = new clsColorRichTextBoxSchema( schema );
            _currentDocumentPath = path;
            _currentTemporyFile = CreateTempFile();
            _sourceRTB.LoadFile( _currentDocumentPath, RichTextBoxStreamType.PlainText );
            _parent = parent;
            autoSave = new AutoSave( this, ref _parent );
            if ( Settings.Default.AutoSaveEnable )
                autoSave.Start();
            beenEdited = false;
        }

        public DocumentForm( string path, clsColorRichTextBoxSchema schema, MainForm parent, bool showHTML ) {
            InitializeComponent();
            this.FormClosing += new FormClosingEventHandler( this.DocumentForm_FormClosing );
            this.Shown += new EventHandler( this.DocumentForm_FormShow );
            this.schema = new clsColorRichTextBoxSchema( schema );
            _currentDocumentPath = path;
            _currentTemporyFile = CreateTempFile();
            _sourceRTB.LoadFile( _currentDocumentPath, RichTextBoxStreamType.PlainText );
            _parent = parent;
            autoSave = new AutoSave( this, ref _parent );
            if ( Settings.Default.AutoSaveEnable )
                autoSave.Start();
            beenEdited = false;

            if ( !showHTML ) {
                designTC.TabPages.RemoveAt( 1 );
                designTC.TabPages.RemoveAt( 1 );
            }
        }

        public void SaveFile() {
            try {
                if ( schema.SchemeType.Equals( "Other" ) ) {
                    if ( _currentDocumentPath.EndsWith( ".rtf" ) ) {
                        _sourceRTB.SaveFile( _currentDocumentPath, RichTextBoxStreamType.RichText );
                        beenEdited = false;
                    }
                    else {
                        _sourceRTB.SaveFile( _currentDocumentPath, RichTextBoxStreamType.PlainText );
                        beenEdited = false;
                    }
                }
                else {
                    if ( wasDesigning )
                        _sourceRTB.Text = _designWB.DocumentText;
                    _sourceRTB.SaveFile( _currentDocumentPath, RichTextBoxStreamType.PlainText );
                    beenEdited = false;
                }
            }
            catch ( Exception ex ) {
                new BugReporter.BugReporterForm( Application.ProductName,
                  Application.ProductVersion, ex.ToString(), ex.Message ).Show();
            }
        }

        public void SaveFile( string path ) {
            try {
                if ( schema.SchemeType.Equals( "Other" ) ) {
                    if ( _currentDocumentPath.EndsWith( ".rtf" ) ) {
                        _sourceRTB.SaveFile( path, RichTextBoxStreamType.RichText );
                        _currentDocumentPath = path;
                        beenEdited = false;
                    }
                    else {
                        _sourceRTB.SaveFile( path, RichTextBoxStreamType.PlainText );
                        _currentDocumentPath = path;
                        beenEdited = false;
                    }
                }
                else {
                    if ( wasDesigning )
                        _sourceRTB.Text = _designWB.Document.Body.InnerHtml;
                    _sourceRTB.SaveFile( path, RichTextBoxStreamType.PlainText );
                    _currentDocumentPath = path;
                    beenEdited = false;
                }
            }
            catch ( Exception ex ) {
                new BugReporter.BugReporterForm( Application.ProductName,
                  Application.ProductVersion, ex.ToString(), ex.Message ).Show();
            }
        }

        #endregion

        #region " Private Methods "

        private void DocumentForm_Load( object sender, EventArgs e ) {
            rtb = new clsColorRichTextBox( _sourceRTB, schema );
            rtb.RecolorEntireText();
            _designWB.DocumentText = _sourceRTB.Text;
            docv = _designWB.Document.DomDocument as IHTMLDocument2;
            docv.designMode = "On";
            isLoaded = true;
        }

        private void tabControl1_SelectedIndexChange( object sender, EventArgs e ) {
            if ( designTC.SelectedIndex == 0 )
                ViewSource();
            else if ( designTC.SelectedIndex == 1 )
                ViewDesigner();
            else if ( designTC.SelectedIndex == 2 )
                ViewBrowser();
        }

        private void ViewSource() {
            if ( wasDesigning ) {
                wasDesigning = false;
                _sourceRTB.Text = _designWB.DocumentText;
            }
            rtb.RecolorEntireText();
        }

        private void ViewDesigner() {
            _designWB.DocumentText = _sourceRTB.Text;
            wasDesigning = true;
        }

        private void ViewBrowser() {
            if ( wasDesigning ) {
                wasDesigning = false;
                _sourceRTB.Text = _designWB.DocumentText;
            }

            _sourceRTB.SaveFile( _currentTemporyFile, RichTextBoxStreamType.PlainText );
            _browserWB.Navigate( _currentTemporyFile );

        }

        private int GetFontSize( float size ) {
            if ( size > 0 && size <= 9.75f )
                return 1;
            else if ( size > 9.75f && size <= 12.5f )
                return 2;
            else if ( size > 12.5f && size <= 15.6f )
                return 3;
            else if ( size > 15.6f && size <= 21.5f )
                return 4;
            else if ( size > 21.5f && size <= 23.4f )
                return 5;
            else if ( size > 23.4f && size <= 31.2f )
                return 6;
            else if ( size > 31.2f && size <= 46.8f )
                return 7;
            else
                return 8;
        }

        private void DocumentForm_FormClosing( object sender, FormClosingEventArgs e ) {
            autoSave.Restart();
            if ( beenEdited ) {

                switch ( MessageBox.Show( "Would you like to save your file?", "Save?", MessageBoxButtons.YesNoCancel ) ) {
                    case DialogResult.Cancel:
                        e.Cancel = true;
                        break;
                    case DialogResult.No:
                        _parent.CurrentForms.Remove( this );
                        break;
                    case DialogResult.Yes:
                        SaveFile();
                        _parent.CurrentForms.Remove( this );
                        break;
                }
            }
            autoSave.Stop();
        }

        private void DocumentForm_FormShow( object sender, EventArgs e ) {
            beenEdited = false;
        }

        private void _sourceRTB_TextChanged( object sender, EventArgs e ) {
            if ( isLoaded ) {
                beenEdited = true;
            }
        }

        private void InsertText( string text ) {
            IHTMLTxtRange range =
            docv.selection.createRange() as IHTMLTxtRange;
            range.pasteHTML( text );
            range.collapse( false );
            range.select();
        }

        private void _sourceRTB_KeyPress( object sender, KeyPressEventArgs e ) {
            /*
            if ( e.KeyChar == Convert.ToChar( Keys.Enter ) ) {
                e.Handled = true;
                int pos;
                pos = _sourceRTB.SelectionStart;
                int lineNum = _sourceRTB.GetLineFromCharIndex( pos ) - 1;
                string currentLineStr = _sourceRTB.Lines[ lineNum ];
                int firstChar = 0;
                while ( firstChar != currentLineStr.Length ) {
                    if ( !char.IsWhiteSpace( currentLineStr[ firstChar ] ) )
                        continue;
                    else
                        firstChar = ++firstChar;
                }

                string indent = currentLineStr.Substring( 0, firstChar );
                _sourceRTB.SelectedText = indent; 
            }
             */
        }

        private string CreateTempFile() {

            string path = Application.StartupPath + Settings.Default.TemporayFileDir;
            DirectoryInfo info = new DirectoryInfo( path );
            int size = info.GetFiles().Length;

            if ( size > 0 )
                path += "\\tempFile-" + size + "-.html";
            else
                path += "\\tempFile-0-.html";

            FileStream file = File.Create( path );
            file.Close();

            return path;
        }

        #endregion

        #region " Toolbar Click Events "

        private void boldToolStripButton_Click( object sender, EventArgs e ) {
            _designWB.Document.ExecCommand( "Bold", false, null );
        }

        private void italicToolStripButton_Click( object sender, EventArgs e ) {
            _designWB.Document.ExecCommand( "Italic", false, null );
        }

        private void underlineToolStripButton_Click( object sender, EventArgs e ) {
            _designWB.Document.ExecCommand( "Underline", false, null );
        }

        private void fontToolStripButton_Click( object sender, EventArgs e ) {
            if ( fontDialog1.ShowDialog( this ) == DialogResult.OK ) {
                Font font = fontDialog1.Font;
                Color color = fontDialog1.Color;
                _designWB.Document.ExecCommand( "FontName", false, font.Name );
                _designWB.Document.ExecCommand( "FontSize", false, GetFontSize( font.SizeInPoints ) );
                _designWB.Document.ExecCommand( "ForeColor", false, ColorTranslator.ToHtml( color ) );
                if ( font.Bold )
                    _designWB.Document.ExecCommand( "Bold", false, null );
                if ( font.Strikeout )
                    _designWB.Document.ExecCommand( "StrikeThrough", false, null );
                if ( font.Underline )
                    _designWB.Document.ExecCommand( "Underline", false, null );
            }
        }

        private void hlToolStripButton_Click( object sender, EventArgs e ) {
            _designWB.Document.ExecCommand( "CreateLink", true, null );
        }

        private void imageToolStripButton_Click( object sender, EventArgs e ) {
            _designWB.Document.ExecCommand( "InsertImage", true, null );
        }

        private void hrToolStripButton_Click( object sender, EventArgs e ) {
            _designWB.Document.ExecCommand( "InsertHorizontalRule", false, null );
        }

        private void brToolStripButton_Click( object sender, EventArgs e ) {
            InsertText( @"<BR>" );
        }

        private void buttonToolStripMenuItem_Click( object sender, EventArgs e ) {
            _designWB.Document.ExecCommand( "InsertInputButton", false, null );
        }

        private void textboxToolStripMenuItem_Click( object sender, EventArgs e ) {
            _designWB.Document.ExecCommand( "InsertInputText", true, null );
        }

        private void checkboxToolStripMenuItem_Click( object sender, EventArgs e ) {
            _designWB.Document.ExecCommand( "InsertInputCheckbox", false, null );
        }

        private void radioButtonToolStripMenuItem_Click( object sender, EventArgs e ) {
            _designWB.Document.ExecCommand( "InsertInputRadio", false, null );
        }

        private void fileUploadToolStripMenuItem_Click( object sender, EventArgs e ) {
            _designWB.Document.ExecCommand( "InsertInputFileUpload", false, null );
        }

        private void textareaToolStripMenuItem_Click( object sender, EventArgs e ) {
            _designWB.Document.ExecCommand( "InsertTextArea", false, null );
        }

        private void dropDownListToolStripMenuItem_Click( object sender, EventArgs e ) {
            _designWB.Document.ExecCommand( "InsertSelectDropDown", false, null );
        }

        private void hiddenToolStripMenuItem_Click( object sender, EventArgs e ) {
            _designWB.Document.ExecCommand( "InsertInputHidden", true, null );
        }

        private void passwordToolStripMenuItem_Click( object sender, EventArgs e ) {
            _designWB.Document.ExecCommand( "InsertInputPassword", false, null );
        }

        private void formToolStripMenuItem_Click( object sender, EventArgs e ) {
            InsertText( "<FORM METHOD=GET></FORM>" );
        }        

        private void divToolStripButton_Click( object sender, EventArgs e ) {
            InsertText( "<DIV></DIV>" );
        }

        private void spanToolStripButton_Click( object sender, EventArgs e ) {
            InsertText( "<SPAN></SPAN>" );
        }

        private void centerToolStripMenuItem_Click( object sender, EventArgs e ) {
            _designWB.Document.ExecCommand( "JustifyCenter", false, null );
        }

        private void leftToolStripMenuItem_Click( object sender, EventArgs e ) {
            _designWB.Document.ExecCommand( "JustifyLeft", false, null );
        }

        private void rightToolStripMenuItem_Click( object sender, EventArgs e ) {
            _designWB.Document.ExecCommand( "JustifyRight", false, null );
        }

        private void undoToolStripMenuItem_Click( object sender, EventArgs e ) {
            _sourceRTB.Undo();
        }

        private void redoToolStripMenuItem_Click( object sender, EventArgs e ) {
            _sourceRTB.Redo();
        }

        private void cutToolStripMenuItem_Click( object sender, EventArgs e ) {
            _sourceRTB.Cut();
        }

        private void copyToolStripMenuItem_Click( object sender, EventArgs e ) {
            _sourceRTB.Copy();
        }

        private void pasteToolStripMenuItem_Click( object sender, EventArgs e ) {
            _sourceRTB.Paste();
        }

        #endregion

        private void DocumentForm_Enter( object sender, EventArgs e ) {
            _parent.ActiveChildForm = this;
        }

        private void DocumentForm_Leave( object sender, EventArgs e ) {
            _parent.ActiveChildForm = null;
        }
    }
}
